<?php
/**
 * Created by PhpStorm.
 * User: Mizuki
 * Date: 2019/7/10
 * Time: 11:16
 */
namespace Api\Logic;

class WeixinLogic extends BaseLogic {
    /*
  * 微信openid
  */
    public function oauth()
    {
        if (isset($_POST['code'])) {
            $code = $_POST['code'];
            $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . C('APPID') . '&secret=' . C('APPSECRET') . '&js_code=' . $code . '&grant_type=authorization_code';
            $content = file_get_contents($url);
            $de_json = json_decode($content, TRUE);
            $openid = $de_json['openid'];
            if (is_null($openid)) {
                return $this->setError($de_json['errmsg']);
            }
            return $openid;
        } else {
            return $this->setError('NO CODE');
        }
    }

    /*
     * 用户登录
     */
    public function userLogin()
    {
        $code = I('code');
        $grant_type = I('grant_type');
        $openid = $this->oauth();
        if($openid['success'] == FALSE) {
            return $this->result;
        }
        $USER = D('User');
        $info = $USER->getInfoByOpenid($openid);
        if(isset($info['success']) && $info['success'] == FALSE) {
            // 数据库没数据，则写入
            $data = [
                'status' => 1,
                'openid' =>$openid,
                'gmtCreate' => time(),
            ];
            $data['uid'] = $USER->add($data);
            $data['session_id'] = session_id();
            session('uid', $data['uid']);
            return $this->setSuccess('第一次登录，请完善信息', 2, $data);
        } else {
            $info['session_id'] = session_id();
            session('uid', $info['iduser']);
            if(chop($info['name']) == ''){
                // 有数据则判断是否完善
                return $this->setSuccess('请完善信息', 1, $info);
            } else {
                return $this->setSuccess('登陆成功', 0, $info);
            }
        }
    }
}